package uk.co.q3c.deplan.client.util;

import uk.co.q3c.deplan.client.domain.DomainKind;
import uk.co.q3c.deplan.client.domain.DomainObject;
import uk.co.q3c.deplan.client.ui.view.Q3CoreView;
import uk.co.q3c.deplan.client.ui.view.Viewtags;

/**
 * History token deliberately uses the same construct for the referred object as
 * the app engine KeyFactory createAsKey method, taking the simpleName element
 * of the class name and the long id of the domain object. The view name is
 * added to complete the token.
 * 
 * @author David Sowerby 28 Mar 2010
 * 
 */
public class HistoryToken {

	/**
	 * returns a history token to be placed in the URL to mark a specific object
	 * 
	 * @param dob
	 * @return
	 */
	public static String constructHistoryToken(String viewName, DomainObject dob) {
		StringBuilder buf = new StringBuilder();
		buf.append(viewName + ":" + dob.getKind() + ":"
				+ Long.toString(dob.getKeyId()));
		return buf.toString();

	}

	/**
	 * returns a history token to be placed in the URL to mark a specific object
	 * 
	 * @param dob
	 * @return
	 */
	public static String constructHistoryToken(HistoryTokenRecord htr) {
		StringBuilder buf = new StringBuilder();
		buf.append(htr.viewName + ":" + htr.kind + ":" + Long.toString(htr.id));
		return buf.toString();

	}

	public static HistoryTokenRecord constructRecord(Q3CoreView view,
			DomainObject objectInView) {
		HistoryTokenRecord htr = new HistoryTokenRecord();
		htr.viewName = view.viewTag();
		htr.kind = objectInView.getKind();
		htr.id = objectInView.getKeyId();
		return htr;
	}

	/**
	 * decomposes a history token and returns its constituent parts (see
	 * {@link HistoryTokenRecord})
	 * 
	 * @param historyToken
	 * @return
	 */

	public static HistoryTokenRecord parseToken(String historyToken) {
		String[] parts = historyToken.split(":");
		HistoryTokenRecord htr = new HistoryTokenRecord();
		htr.viewName = Viewtags.valueOf(parts[0]);
		htr.kind = DomainKind.valueOf(parts[1]);
		htr.id = Long.parseLong(parts[2]);
		return htr;
	}

}
